# /usr/bin/env python
# -*- coding: utf-8 -*-

"""
自动化方式抓取 bing 今日美图
"""


import os
import re
import sys
import time
import urllib
from datetime import datetime
from os import path

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

reload(sys)
sys.setdefaultencoding('utf-8')


def get_background_image(element, retry_left=3):
    image = element.value_of_css_property('background-image')
    image = None if 'none' == image else image
    if None is image and 0 < retry_left:
        time.sleep(0.500)  # 唉，操蛋，等一会儿，让样式应用起来
        return get_background_image(element, retry_left - 1)

    return image


def main():
    args = sys.argv[1:]
    if 0 == len(args):
        base_dir = 'runtime/bing'
    else:
        base_dir = args[0]

    if not path.exists(base_dir):
        os.mkdir(base_dir)

    options = webdriver.FirefoxOptions()
    options.headless = True  # 设置为 无头模式，不显示出来
    driver = webdriver.Firefox(options=options)
    try:
        driver.get('https://cn.bing.com/')
        WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.ID, 'bgDiv')))

        element = driver.find_element_by_id('bgDiv')
        image = get_background_image(element)
        if None is image:
            raise RuntimeWarning('获取不到元素的 background-image 样式')

        regex = re.compile(r'url\("(\S*)"\)')
        regex.match(image)
        matches = regex.match(image)
        url = matches.group(1)
        print('%s:将要下载图片：%s' % (datetime.now(), url))

        filename = path.join(base_dir, path.basename(url))
        urllib.urlretrieve(url, filename=filename)
        print('%s:今日美图已成功下载到：%s`' % (datetime.now(), filename))
    finally:
        driver.quit()


if '__main__' == __name__:
    main()
